import 'dart:io';
import 'package:socket_io/socket_io.dart';

void main() async {
  var server = Server();
  var httpServer = await HttpServer.bind('0.0.0.0', 3000);

  // 提供静态文件服务
  httpServer.listen((HttpRequest request) {
    final String path = request.uri.path == '/' ? '/index.html' : request.uri.path;
    final File file = File('./static/files$path');

    if (file.existsSync()) {
      request.response.headers.contentType = ContentType.html;
      file.openRead().pipe(request.response);
    } else {
      request.response.statusCode = HttpStatus.notFound;
      request.response.close();
    }
  });

  // 绑定 Socket.IO 服务
  server.attach(httpServer);

  // 处理 Socket.IO 连接
  server.on('connection', (client) {
    print('新客户端已连接');
    client.on('message', (data) {
      print('收到消息: $data');
      client.emit('response', '你好，客户端');
    });
    client.on('disconnect', () {
      print('客户端已断开连接');
    });
  });

  print('服务器运行在 http://localhost:3000');
}
